package com.tpc.jginterface.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.tpc.jginterface.model.KeyBean;
import com.tpc.jginterface.util.ApiRequestUtil;
import com.tpc.jginterface.util.TraceCodeUtil;
import com.tpc.jginterface.util.http.BodyType;
import com.tpc.jginterface.util.http.OkHttpClients;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Slf4j
@Component
public class PurOutService {
    @Value("${org.no}")
    private String orgNo;

    @Value("${API.URL}")
    private String APIURL;

    @Autowired
    private ApiRequestUtil apiRequestUtil;

    public void uploadPurOut() {
        log.info("===============================【采退开始】===============================");
        try {
            // 构建请求参数
            JSONObject requestBody = new JSONObject();
            requestBody.put("P_ACTION", "SELECT");
            requestBody.put("P_PROC_NAME", "PROC_INTERFACE_DO_PUROUT");
            requestBody.put("P_SIGN", UUID.randomUUID().toString());
            requestBody.put("P_ORGNO", orgNo);
            log.info("获取数据请求参数：{}", requestBody);
            // 发送请求
            String responseStr = OkHttpClients.builder()
                    .setUri(APIURL)
                    .addReqData(requestBody.toString())
                    .post(BodyType.JSON_BODY)
                    .sync();
            log.info("获取数据响应结果：{}", responseStr);

            // 解析响应
            JSONObject responseJSON = JSONObject.parseObject(responseStr);
            JSONObject data = null;
            if (responseJSON != null && "200".equals(responseJSON.getString("code"))) {
                data = responseJSON.getJSONObject("data")
                        .getJSONArray("DATASET")
                        .getJSONObject(0);
                if (data.getString("id") != null) {
                    requestBody.put("P_ID", data.getString("id"));
                }
            } else {
                log.error("请求失败，响应码：{}", responseJSON != null ? responseJSON.getString("code") : "null");
            }
            KeyBean keyBean = new KeyBean();
            if (data != null) {
                keyBean = JSONObject.parseObject(JSONObject.toJSONString(data), KeyBean.class);
            }
            requestBody.put("P_ACTION", "SELECTDETAIL");
            JSONObject dataDetailJSON = null;
            JSONArray dataDtailJSONArray = null;
            String responseStrDetail = OkHttpClients.builder()
                    .setUri(APIURL)
                    .addReqData(requestBody.toString())
                    .post(BodyType.JSON_BODY)
                    .sync();
            dataDetailJSON = JSONObject.parseObject(responseStrDetail);
            if (responseStrDetail != null && "200".equals(dataDetailJSON.getString("code"))) {
                dataDtailJSONArray = dataDetailJSON.getJSONObject("data")
                        .getJSONArray("DATASET");
                if (dataDtailJSONArray != null && dataDtailJSONArray.size() > 0) {
                    for (int i = 0; i < dataDtailJSONArray.size(); i++) {
                        JSONObject detail = dataDtailJSONArray.getJSONObject(i);
                        String tracCodeStr = detail.getString("tracCode");
                        String drugCode = detail.getString("drugCode");
                        if (tracCodeStr != null && !tracCodeStr.trim().isEmpty()) {
                            JSONArray tracCodeArray = TraceCodeUtil.convertTracCodeToJsonArray(tracCodeStr, drugCode);
                            detail.put("tracCode", tracCodeArray);
                        }
                    }
                }
                if (data != null) {
                    data.put("detail", dataDtailJSONArray);
                }

            } else {
                log.error("请求失败，响应码：{}", responseJSON != null ? responseJSON.getString("code") : "null");
            }
            log.info("上传数据请求参数：{}", data);
            String rfResponseStr = apiRequestUtil.sendEncryptedRequest("/api/v1/service/4002", data.toString(),
                    keyBean);
            log.info("上传数据响应结果：{}", rfResponseStr);
            requestBody.put("P_REQUESTINFO", data.toString());
            requestBody.put("P_RESPONSEINFO", rfResponseStr);
            requestBody.put("P_ACTION", "UPDATE");
            if (JSONObject.parseObject(rfResponseStr).getInteger("code") != null) {
                requestBody.put("P_CODE", JSONObject.parseObject(rfResponseStr).getInteger("code"));
            } else {
                requestBody.put("P_CODE", "999999");
            }
            log.info("回写数据请求参数：{}", requestBody);
            OkHttpClients.builder()
                    .setUri(APIURL)
                    .addReqData(requestBody.toString())
                    .post(BodyType.JSON_BODY)
                    .sync();
        } catch (Exception e) {
            log.error("请求发生异常：", e);
        }
        log.info("===============================【采退结束】===============================");
    }

}
